﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;

using Eforcity.Common35;
using Eforcity.Data.Common35;
using Eforcity.EbayApiDb;
using Eforcity.EbayApiDb.DbTypes;

using Eforcity.EbayApi.Ebay.TradingApi.Webservice;

namespace Eforcity.EbayApi
{
    public partial class EbayTradingMdl
    {
        public static void GetActiveListingSellerEvents(EbayApiBaseInputType inputPara, int sellerId, int minInterval, int minWrap, int extendCollectTime, int defaultTimeBefore, EbayConsoleProcessType consoleProcess)
        {
            DateTime dtSellerStart = DateTime.Now;
            int loopCount = 0;

            EbayTradingApi ebayApi =
                new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                    inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);

            DateTime modUTCTimeFrom = DateTime.Parse("1901-01-01");//DBNUll Datetime
            DateTime modUTCTimeTo = DateTime.Parse("1901-01-01");

            bool finished = false;
            bool hasError = false;
            modUTCTimeFrom = EbaySellerEventData.GetSellerEventsLastCollectUTCTime(sellerId, defaultTimeBefore, inputPara.EbayStatConn).AddMinutes(-extendCollectTime);
            while (!finished)//Loop Until lastCollectTIme=DateTime.Now,Split 
            {
                EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                //modUTCTimeFrom = EbaySellerEventData.GetSellerEventsLastCollectUTCTime(sellerId, defaultTimeBefore, inputPara.EbayStatConn);
                modUTCTimeTo = modUTCTimeFrom.AddMinutes(minInterval);
                if (!hasError)
                {
                    modUTCTimeFrom = modUTCTimeFrom.AddSeconds(-minWrap);
                }

                DateTime extendNowTime = DateTime.Now.ToUniversalTime().AddMinutes(extendCollectTime);
                if (modUTCTimeTo >= extendNowTime)
                {   // Get most recently   sellerEvents
                    modUTCTimeTo = extendNowTime;
                    modUTCTimeFrom = modUTCTimeTo.AddMinutes(-minInterval).AddSeconds(-minWrap);
                    finished = true;
                }

                int retry = 0;
                bool success = false;
                bool needReduceTime;
                while (success == false && retry <= inputPara.ApiMaxRetry)
                {
                    if (modUTCTimeTo < modUTCTimeFrom)
                    {
                        break;
                    }
                    //Request here
                    List<ActiveListingSalesType> activeListingSalesList =
                        ebayApi.GetSellerEvents(sellerId, modUTCTimeFrom, modUTCTimeTo, out needReduceTime);
                    if (activeListingSalesList != null)
                    {
                        EbaySellerEventData.InsertRawActiveListing(activeListingSalesList, inputPara.EbayStatConn);
                        if (modUTCTimeTo == extendNowTime)
                        {
                            modUTCTimeTo = extendNowTime.AddMinutes(-extendCollectTime);
                        }
                        EbaySellerEventData.InsertSellerEventsLastCollectUTCTime(sellerId, modUTCTimeTo, inputPara.EbayStatConn);
                        modUTCTimeFrom = EbaySellerEventData.GetSellerEventsLastCollectUTCTime(sellerId, defaultTimeBefore, inputPara.EbayStatConn);
                        success = true;
                    }
                    else if (!needReduceTime)
                    {
                        success = true;
                    }
                    else
                    {
                        retry++;
                        System.Threading.Thread.Sleep(inputPara.RetrySleepTime);//5000  
                        //Update by Joseph 20100525
                        //modUTCTimeTo = modUTCTimeTo.AddMinutes(-minInterval / 2);
                        modUTCTimeTo = modUTCTimeTo.AddSeconds(-(minInterval * 60) / (int)Math.Pow(2, retry));
                    }
                    loopCount++;
                }
                hasError = retry > 0;
            }
            try
            {
                DateTime dtSellerEnd = DateTime.Now;
                TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
            }
            catch (Exception ex)
            {
                EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
            }
        }

        public static void GetSellerActiveListingByStartDate(GetSellerListingInputType inputPara, BackgroundWorker bw)
        {
            //EbayTradingApi ebayApi = new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry, inputPara.SessionCallLimit, inputPara.EbayStatConn);
            List<ActiveListingProcHistType> procHistList = EbayActiveListingData.GetProcHistActiveListing(inputPara.EbayStatConn);
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = AppIdEnum.CAL;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            //For each Seller, if not hist, then create one, else, continue
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;

                        EbayTradingApi ebayApi =
                       new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                           inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);


                        //Get Seller Name For Report Progress
                        string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                        bool isOwner = EbaySellerData.IsAcctOwner(sellerId, inputPara.EbayStatConn);

                        ActiveListingProcHistType procHist =
                            procHistList.Find(delegate(ActiveListingProcHistType p) { return p.SellerId == sellerId; });

                        if (procHist != null)
                        {
                            //Check if it is completed
                            if (procHist.Status == 1)
                            {
                                bw.ReportProgress(0, sellerName + " has been completed");
                                continue;
                            }
                        }
                        else
                        {

                            //Insert
                            EbayActiveListingData.InsertProcHistActiveListing(sellerId, inputPara.DateUTCFrom, inputPara.DateUTCTo, inputPara.EbayStatConn);

                            procHist = new ActiveListingProcHistType();
                            procHist.SellerId = sellerId;
                            procHist.StartDateFrom = inputPara.DateUTCFrom;
                            procHist.StartDateTo = inputPara.DateUTCTo;
                            procHist.StartDateCurrent = inputPara.DateUTCFrom;
                        }

                        bool isBreak = false;
                        DateTime processStartTimeFrom = procHist.StartDateCurrent;
                        DateTime processStartTimeTo = procHist.StartDateCurrent.AddHours(1);
                        while (processStartTimeFrom < procHist.StartDateTo)
                        {
                            EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                            if (bw != null)
                            {
                                bw.ReportProgress(0, "[" + sellerName + "] - " +
                                    "UTC:  " + processStartTimeFrom);
                            }
                            if (processStartTimeTo > DateTime.Now.ToUniversalTime().AddMinutes(-30))
                            {
                                if (bw != null)
                                {
                                    bw.ReportProgress(0, "The DateTime is not Finished. " + processStartTimeTo);
                                }
                                break;
                            }
                            loopCount++;

                            //List<EbayListingItemType> listingResponseList =
                            //            ebayApi.GetSellerList(sellerId, sellerName, isOwner, processStartTimeFrom, processStartTimeTo, false, inputPara.ListingEntriesPerPage);

                            List<EbayListingItemType> listingResponseList =
                                       ebayApi.GetSellerList(1273, "la_maison_des_prix_fous", false, ConvertUtility.ToDateTime("2010-8-1 23:59:00"), ConvertUtility.ToDateTime("2010-8-31 1:01:00"), false, 200);


                            if (listingResponseList != null)
                            {
                                try
                                {
                                    EbayActiveListingData.InsertRawActiveListing(listingResponseList, inputPara.EbayStatConn);
                                    EbayActiveListingData.UpdateProcHistActiveListingCurrentProcDate
                                        (sellerId, processStartTimeTo, inputPara.EbayStatConn);
                                }
                                catch (Exception ex)
                                {
                                    //Log down the DB errors
                                    EbayErrorData.InsertErrorGetSellerList(sellerId, processStartTimeFrom, processStartTimeTo, 0, 0, EbayErrorTypeEnum.SysLevel, -2, ex.Message, inputPara.EbayStatConn);
                                    bw.ReportProgress(0, ex.ToString());
                                    isBreak = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Error, Skip and process other account first                        
                                bw.ReportProgress(0, "Error in Web Service, Retry Later...");
                                isBreak = true;
                                break;
                            }
                            processStartTimeFrom = processStartTimeTo;
                            processStartTimeTo = processStartTimeFrom.AddHours(1);
                        }

                        if (!isBreak && processStartTimeFrom >= procHist.StartDateTo)
                        {
                            //EbayActiveListingData.UpdateProcHistActiveListingStatus(sellerId, 1, inputPara.EbayStatConn);
                            EbayActiveListingData.DeleteProcHistActiveListing(sellerId, inputPara.EbayStatConn);
                            EbaySellerData.UpdateSellerRecollect(sellerId, false, inputPara.EbayStatConn);
                        }

                        //EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }

            //Report Progress
            bw.ReportProgress(100, "Completed");
        }

        public static void GetActiveBidders(GetAllBiddersInputType inputPara, BackgroundWorker bw)
        {
            DateTime startDate = DateTime.UtcNow.AddDays(-inputPara.StartDateBefore);
            DateTime lastUpdate = DateTime.UtcNow.AddDays(-inputPara.LastUpdateBefore);
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = inputPara.IsGTC ? AppIdEnum.CAGB : AppIdEnum.CAB;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            //SellerLoop
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;
                        try
                        {
                            EbayTradingApi ebayApi =
                            new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);

                            string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                            List<Int64> itemIdList = new List<long>();
                            if (inputPara.IsGTC)
                            {
                                itemIdList = EbayActiveListingData.GetActiveGTCItemIdList(sellerId, lastUpdate, inputPara.MaxSoldValue, inputPara.EbayStatConn);
                            }
                            else
                            {
                                itemIdList = EbayActiveListingData.GetActiveItemIdList(sellerId, startDate, lastUpdate, inputPara.MaxSoldValue, inputPara.EbayStatConn);
                            }

                            //Batch Start Time (CutOffTime)
                            DateTime cutoffTime = DateTime.Now;

                            //BatchLoop
                            for (int idx = 0; idx < itemIdList.Count; idx += inputPara.BidderProcessLot)
                            {
                                EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                                try
                                {
                                    int batchSize = inputPara.BidderProcessLot;
                                    if (itemIdList.Count - idx < inputPara.BidderProcessLot)
                                    {
                                        batchSize = itemIdList.Count - idx;
                                    }
                                    List<Int64> batchItemIdList = itemIdList.GetRange(idx, batchSize);

                                    if (bw != null && batchItemIdList.Count > 0)
                                    {
                                        bw.ReportProgress(0, "Processing [" + sellerName + "]: " + (idx + 1) + " - " + (idx + batchSize) + " of " + itemIdList.Count);
                                    }

                                    List<EbayItemBiddersType> ebayItemBiddersList = ebayApi.GetAllBidders(batchItemIdList, bw);
                                    if (ebayItemBiddersList != null)
                                    {
                                        //InsertLoop
                                        foreach (EbayItemBiddersType ebayItemBidders in ebayItemBiddersList)
                                        {
                                            try
                                            {
                                                long itemId = ebayItemBidders.ItemId;
                                                List<EbayBidderType> ebayBidderList = ebayItemBidders.EbayBidderList;
                                                if (itemId > 0 && ebayBidderList != null)
                                                {
                                                    EbayBidderData.InsertActiveBidderList(itemId, ebayBidderList, inputPara.EbayStatConn);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                //Report error
                                                bw.ReportProgress(0, "Error: InsertLoop - " + ex.Message);
                                                //By Pass
                                                continue;
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    //Report error
                                    bw.ReportProgress(0, "Error: BatchLoop - " + ex.Message);
                                    //By Pass
                                    continue;
                                }
                            }

                            EbayBidderData.InsertProcHistActiveBidder(sellerId, cutoffTime, inputPara.IsGTC, inputPara.EbayStatConn);
                        }
                        catch (Exception ex)
                        {
                            //Report error
                            bw.ReportProgress(0, "Error: SellerLoop - " + ex.Message);
                            //By Pass
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }
        }

        public static void GetDvdUpc(GetItemInputType inputPara, BackgroundWorker bw)
        {
            bw.ReportProgress(0, "Starting Downloading Process...");
            List<long> processQueue = null;
            string upc = string.Empty;
            int progress = 0;
            int currentCount = 1;
            decimal totalCount = 0;

            foreach (int sellerId in inputPara.SellerIdList)
            {
                try
                {
                    EbayTradingApi eBayApi =
                       new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                           inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail, inputPara.EbayStatConn);

                    progress = 0;
                    currentCount = 1;

                    string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                    bw.ReportProgress(0, "Loading Items: " + sellerName);
                    processQueue = EbayListingData.GetNullDvdUpc(inputPara.DateFrom, inputPara.DateTo, sellerId, inputPara.EbayStatConn);
                    totalCount = processQueue.Count;

                    foreach (long itemid in processQueue)
                    {
                        try
                        {
                            #region GetUpc
                            AttributeSetType[] attributeSetTypeArr = eBayApi.GetItem(itemid);
                            if (attributeSetTypeArr != null)
                            {
                                foreach (AttributeSetType attributeSetType in attributeSetTypeArr)
                                {
                                    //DVD UPC = 25008
                                    foreach (AttributeType attributeType in attributeSetType.Attribute)
                                    {
                                        if (attributeType.attributeID == 25008)
                                        {
                                            //Found all value, noramlly only conatin 1 recond
                                            foreach (ValType valType in attributeType.Value)
                                            {
                                                if (valType.ValueLiteral.Trim() != "" && valType.ValueLiteral.Length <= 15)
                                                {
                                                    upc = ConvertUtility.Trim(valType.ValueLiteral);
                                                }
                                            }

                                        }
                                    }
                                }
                            }
                            #endregion
                            try
                            {
                                EbayListingData.InsertRawDvdUpc(itemid, upc, inputPara.EbayStatConn);
                            }
                            catch (Exception ex)
                            {
                                //Not sure why there could be a duplicate key, by pass and retry later; or other error
                                bw.ReportProgress(0, "Error:" + ex.Message);
                            }
                            progress = (int)(((decimal)currentCount / totalCount) * 100);
                            bw.ReportProgress(progress, sellerName + ": " + currentCount + "/" + totalCount);
                            currentCount++;
                        }
                        catch (Exception ex)
                        {
                            bw.ReportProgress(0, "Error:" + ex.Message);
                            //ByPass
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    bw.ReportProgress(0, "Error:" + ex.Message);
                    //ByPass
                    continue;
                }
            }
        }

        public static void GetFeedback(GetFeedbackInputType inputPara, BackgroundWorker bw)
        {
            bw.ReportProgress(0, "Starting Request Feedback ... ");
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = AppIdEnum.CF;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);

            //SellerLoop
            foreach (int sellerId in inputPara.SellerIdList)
            {
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;
                        try
                        {
                            EbayTradingApi eBayApi =
                                    new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                        inputPara.SessionCallLimit, sellerId, inputPara.AllowNonSpecificCredential, inputPara.MinCallAvail, inputPara.EbayStatConn);

                            string sellerName = EbaySellerData.GetEbaySellerName(sellerId, inputPara.EbayStatConn);
                            bw.ReportProgress(0, "Get " + sellerName + " Feedback Summary...");
                            loopCount++;
                            if (inputPara.IsFeedbackSummary == false)
                            {
                                //1, Get The lastest FeedbackId, Process Stop when the feedbackId is matched
                                Int64 lastestFeedbackId = EbayFeedbackData.GetLastestFeedBackId(sellerId, inputPara.EbayStatConn);

                                List<EbayFeedbackType> newFeedbackList = new List<EbayFeedbackType>();

                                bool completeFlag = false;
                                int pageNum = 1;
                                while (!completeFlag)
                                {
                                    EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                                    //Get The list, compare
                                    bw.ReportProgress(0, "Loading : " + sellerName + " , Page: " + pageNum);
                                    List<EbayFeedbackType> feedbackList = eBayApi.GetFeedback(sellerId, sellerName, 200, pageNum);
                                    if (feedbackList == null)
                                    {
                                        // It Happens on new account
                                        bw.ReportProgress(0, sellerName + ": No Record Found");
                                        completeFlag = true;
                                        break;
                                    }
                                    else
                                    {
                                        if (lastestFeedbackId != 0)
                                        {
                                            foreach (EbayFeedbackType feedbackdetail in feedbackList)
                                            {
                                                if (feedbackdetail.FeedbackId <= lastestFeedbackId)
                                                {
                                                    completeFlag = true;
                                                }
                                            }

                                            newFeedbackList.AddRange(feedbackList);
                                            pageNum++;
                                        }
                                        else
                                        {
                                            //First block of Feedback
                                            newFeedbackList.AddRange(feedbackList);
                                            completeFlag = true;
                                        }
                                    }
                                }

                                //Save to database
                                if (newFeedbackList.Count > 1)
                                {
                                    EbayFeedbackData.InsertFeedbackList(newFeedbackList, inputPara.EbayStatConn);
                                }
                            }
                            else
                            {
                                Dictionary<int, EbayFeedbackSummaryType> feedbackSummaryDict = eBayApi.GetFeedbackSummary(sellerId, sellerName);//
                                //Save to database
                                if (feedbackSummaryDict != null && feedbackSummaryDict.Count > 0)
                                {
                                    EbayFeedbackData.InsertFeedbackSummaryDict(feedbackSummaryDict, inputPara.EbayStatConn);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            bw.ReportProgress(0, "Error: SellerLoop - " + ex.Message);
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }
        }

        public static void GetMemberMessages(GetMemberMessagesInputType inputPara, BackgroundWorker bw)
        {
            EbayConsoleProcessType consoleProcess = new EbayConsoleProcessType();
            consoleProcess.AppId = AppIdEnum.CMM;
            consoleProcess.HostName = SystemUtility.MachineName;
            consoleProcess.SystemUser = SystemUtility.WindowsUserName;
            consoleProcess.ApproxTimeSpent = EbayConsoleProcessData.GetApproxLoopTime(consoleProcess.AppId, inputPara.EbayStatConn);
            int crossTime = 30;//min
            for (int idx = 0; idx < inputPara.SellerIdList.Count; idx++)
            {
                int sellerId = inputPara.SellerIdList[idx];
                consoleProcess.SellerId = sellerId;
                try
                {
                    bool isExists = EbayConsoleProcessData.IsExistsConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                    DataRow drCompleted = EbayConsoleProcessData.GetCompletedConsoleProcessDr(consoleProcess, inputPara.EbayStatConn);
                    bool isCompleted = drCompleted != null;
                    if (!isExists || isCompleted)
                    {
                        DateTime dtSellerStart = DateTime.Now;
                        if (isCompleted)
                        {
                            EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, "Process Timeout. Host Name: "
                                + ConvertUtility.Trim(drCompleted["HostName"]) + ", System User: "
                                + ConvertUtility.Trim(drCompleted["SystemUser"]), inputPara.EbayStatConn);
                            EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        }
                        EbayConsoleProcessData.InsertConsoleProcess(consoleProcess, inputPara.EbayStatConn);
                        int loopCount = 0;
                        try
                        {

                            EbayTradingApi eBayApi =
                                        new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                                            inputPara.SessionCallLimit, sellerId, false, inputPara.MinCallAvail, inputPara.EbayStatConn);

                            //Get Seller Name For Report Progress
                            string sellerName = inputPara.SellerIdNameDict[sellerId];

                            //Get Last Completed time, and - x min to start
                            DateTime lastCollectTime = EbayMessageData.GetMessageLastCollectTime(sellerId, inputPara.EbayStatConn);
                            if (lastCollectTime == DateTime.MinValue)
                            {
                                lastCollectTime = DateTime.UtcNow.AddDays(-60);
                                EbayMessageData.InsertProcHistMemberMessage(sellerId, lastCollectTime, inputPara.EbayStatConn);
                            }
                            lastCollectTime = lastCollectTime.AddMinutes(-crossTime);
                            //If the time > UTC now, continue (but this should not be happen)
                            if (lastCollectTime > DateTime.UtcNow)
                            {
                                bw.ReportProgress(0, "\t[" + sellerName + "]  last process time(UTC) " + lastCollectTime.ToString("yyyy-MM-dd HH:mm:ss") + FileUtility.NewLine + "\tSkipped......");
                            }

                            while (lastCollectTime < DateTime.Now.ToUniversalTime().AddMinutes(inputPara.RequestMinProcessLot))
                            {
                                EbayConsoleProcessData.UpdateConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                                DateTime processStartTimeFrom = lastCollectTime;
                                DateTime processStartTimeTo = processStartTimeFrom.AddMinutes(inputPara.RequestMinProcessLot);
                                if (bw != null)
                                {
                                    bw.ReportProgress(0, "Processing [" + sellerName + "]" + FileUtility.NewLine +
                                            "\tFrom(UTC):  " + processStartTimeFrom + FileUtility.NewLine +
                                            "\tTo(UTC):    " + processStartTimeTo);
                                }
                                loopCount++;
                                List<EbayMessageType> memberMessageList = eBayApi.GetMemberMessages(sellerId, processStartTimeFrom, processStartTimeTo, inputPara.RequestEntriesPerPage);
                                //It is Possible nothing in response in a specific time and seller
                                //BUT "Null" Means Error, Must Manual Check
                                if (memberMessageList != null)//No error.z
                                {
                                    //Insert to DB
                                    try
                                    {
                                        foreach (EbayMessageType memberMessage in memberMessageList)
                                        {
                                            EbayMessageData.InsertRawMemberMessage(memberMessage, inputPara.EbayStatConn);
                                        }
                                        //update History Table
                                        lastCollectTime = processStartTimeTo;

                                        //ByEric, We only log the date < Now
                                        if (lastCollectTime <= DateTime.UtcNow)
                                        {
                                            if (EbayMessageData.UpdateProcHistMemberMessage(sellerId, lastCollectTime, inputPara.EbayStatConn) != 1)
                                            {
                                                throw new Exception("Update Message Collect History Error.Effect row not 1");
                                            }
                                            if (bw != null)
                                            {
                                                bw.ReportProgress(0, "\tProccessed Success.");
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //Log down the DB errors
                                        EbayErrorData.InsertErrorGetMemberMessages(sellerId, processStartTimeFrom, processStartTimeTo, 0, 0, EbayErrorTypeEnum.SysLevel, -2, ex.Message, inputPara.EbayStatConn);
                                        if (bw != null)
                                        {
                                            bw.ReportProgress(0, "\tProccessed fail due to error.");
                                        }
                                        break;
                                    }
                                }
                                else
                                {
                                    //Logdown the error for later process
                                    if (bw != null)
                                    {
                                        bw.ReportProgress(0, "\tProccessed fail due to API Error. Retry on Next Batch.");
                                    }

                                    //By Eric 20080926
                                    //If there is any error, quite the current account and retry on next batch
                                    break;
                                }
                            }
                            //Report Progress
                            if (bw != null)
                            {
                                bw.ReportProgress(100, "Completed");
                            }

                            if (inputPara.NonStop && idx == inputPara.SellerIdList.Count - 1)
                            {
                                idx = -1;
                            }
                        }
                        catch (Exception ex)
                        {
                            bw.ReportProgress(0, "Error:" + ex.Message);
                            //continue;
                        }
                        EbayConsoleProcessData.DeleteConsoleProcess(consoleProcess, inputPara.EbayStatConn);

                        DateTime dtSellerEnd = DateTime.Now;
                        TimeSpan tsSeller = dtSellerEnd - dtSellerStart;
                        consoleProcess.ProcessTimeSpent = (int)Math.Round(tsSeller.TotalSeconds);
                        consoleProcess.AvgProcessTimeSpent = loopCount > 0 ? (int)Math.Round(tsSeller.TotalSeconds / loopCount) : 0;
                        EbayCommonData.InsertProcHistAppSellerRun(consoleProcess, inputPara.EbayStatConn);
                    }
                }
                catch (Exception ex)
                {
                    EbayConsoleProcessData.InsertConsoleProcessErrorLog(consoleProcess, ex.Message, inputPara.EbayStatConn);
                }
            }//end for seller loop
        }

        public static void GetBiddersByItemTrans(GetItemTransactionsInputType inputPara, BackgroundWorker bw)
        {
            foreach (long itemId in inputPara.ItemIdList)
            {
                try
                {
                    DataRow itemDr = EbayListingData.GetRawListing(itemId, inputPara.EbayStatConn);
                    if (itemDr == null)
                    {
                        bw.ReportProgress(0, "No Item found by " + itemId + ".");
                        continue;
                    }
                    int sellerId = ConvertUtility.ToInt(itemDr["SellerId"]);
                    int listingStatus = ConvertUtility.ToInt(itemDr["ListingStatus"]);
                    if (listingStatus != (int)EbayListingStatusEnum.Ended
                        && listingStatus != (int)EbayListingStatusEnum.GTCRelisted)
                    {
                        try
                        {
                            bw.ReportProgress(0, "By pass: " + itemId + " listing status is '"
                                + Enum.Parse(typeof(EbayListingStatusEnum), listingStatus.ToString()).ToString() + "'");
                        }
                        catch
                        {
                            bw.ReportProgress(0, "ByPass: " + itemId + " unknown listing status.");
                        }
                        continue;
                    }
                    DateTime startDate = ConvertUtility.ToDateTime(itemDr["StartDate"]);
                    if (startDate == DateTime.MinValue)
                    {
                        //Error
                        throw new Exception("Invalid StartDate");
                    }

                    bw.ReportProgress(0, "Processing " + itemId + "...");

                    EbayTradingApi ebayApi =
                        new EbayTradingApi(inputPara.ApiEndPoint, inputPara.ApiMaxRetry,
                            inputPara.SessionCallLimit, sellerId, true, inputPara.MinCallAvail,
                            inputPara.EbayStatConn);
                    
                    List<EbayBidderType> ebayBidderList = ebayApi.GetItemTransactions(itemId, startDate, inputPara.EntriesPerPage, bw.ReportProgress);
                    if (ebayBidderList != null && ebayBidderList.Count > 0)
                    {
                        if (listingStatus == (int)EbayListingStatusEnum.Ended)
                        {
                            EbayBidderData.InsertBidderList(itemId, ebayBidderList, inputPara.EbayStatConn);
                            DataRow newItemDr = EbayListingData.GetRawListing(itemId, inputPara.EbayStatConn);
                            if (newItemDr != null)
                            {
                                int newListingStatus = ConvertUtility.ToInt(newItemDr["ListingStatus"]);
                                if (newListingStatus == (int)EbayListingStatusEnum.Completed)
                                {
                                    bw.ReportProgress(0, "Insert bidders success, removing retry log...");
                                    int delRows = EbayBidderData.DeleteRetryLogGetAllBidders(itemId, inputPara.EbayStatConn);
                                    if (delRows == 1)
                                    {
                                        bw.ReportProgress(0, "Success.");
                                    }
                                    else
                                    {
                                        bw.ReportProgress(0, delRows + " rows deleted.");
                                    }
                                }
                                else
                                {
                                    //Report error
                                    bw.ReportProgress(0, "Error: Insert bidders fail.");
                                    //By Pass
                                    continue;
                                }
                            }
                        }
                        else if (listingStatus == (int)EbayListingStatusEnum.GTCRelisted)
                        {
                            EbayBidderData.InsertGtcBidderList(itemId, ebayBidderList, inputPara.EbayStatConn);
                            DataRow newItemDr = EbayListingData.GetRawListing(itemId, inputPara.EbayStatConn);
                            if (newItemDr != null)
                            {
                                int newListingStatus = ConvertUtility.ToInt(newItemDr["ListingStatus"]);
                                if (newListingStatus == (int)EbayListingStatusEnum.GTCBidderLoaded)
                                {
                                    bw.ReportProgress(0, "Insert bidders success, removing retry log...");
                                    int delRows = EbayBidderData.DeleteRetryLogGetAllBidders(itemId, inputPara.EbayStatConn);
                                    if (delRows == 1)
                                    {
                                        bw.ReportProgress(0, "Success.");
                                    }
                                    else
                                    {
                                        bw.ReportProgress(0, delRows + " rows deleted.");
                                    }
                                }
                                else
                                {
                                    //Report error
                                    bw.ReportProgress(0, "Error: Insert bidders fail.");
                                    //By Pass
                                    continue;
                                }
                            }
                        }
                    }
                    else
                    {
                        bw.ReportProgress(0, "Error: Get bidders fail.");
                    }
                }
                catch (Exception ex)
                {
                    bw.ReportProgress(0, "Error: " + ex.Message);
                    continue;
                }
            }
        }
        public static GetOrdersResponseType GetOrders()
        {
            string apiName = "GetOrders";
            eBayAPIInterfaceService service = new eBayAPIInterfaceService();
            GetOrdersRequestType request = new GetOrdersRequestType();
            request.Version = "";
            request.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            request.CreateTimeFrom = Convert.ToDateTime("2010-3-1");
            request.CreateTimeTo = System.DateTime.Now;
            request.ListingType = ListingTypeCodeType.AdType;
            request.OrderRole = TradingRoleCodeType.Seller;
            request.OrderStatus = OrderStatusCodeType.Completed;

            GetOrdersResponseType response = null;
            response = service.GetOrders(request);
            return response;
        }
    }//end class
}//end namespace
